package ru.kest.babymonitor.service.audio;

import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.util.Log;
import ru.kest.babymonitor.Settings;

/**
 * Class played audio stream from AudioPlayer
 */
public class AudioPlayer implements Runnable {

    private static String TAG = "IPCamBabyMonitorService";

    private final static int AVCODEC_MAX_AUDIO_FRAME_SIZE = 10000;
    private final static int EMPTY_BUFFER_TIMEOUT = 5000;
    AudioTrack mAudioTrack = null;
    Settings settings = Settings.getInstance();

    @Override
    public void run() {

        AudioQueue audioQueue = AudioQueue.getInstance();

        try {
            while ((settings.isAudioOn() || settings.isAudioOnAlarmOn()) && !Thread.interrupted()) {
                short[] pack = audioQueue.getAudioData(EMPTY_BUFFER_TIMEOUT);
//                byte[] pack = audioQueue.getAudioData();
                if (pack == null) {
                    if (mAudioTrack != null && mAudioTrack.getPlayState() == AudioTrack.PLAYSTATE_PLAYING) {
                        mAudioTrack.stop();
                        Log.i(TAG, "AudioPlayer is stopped");
                    }
                } else {
                    getAudioTrack().write(pack, 0, pack.length);
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "AudioPlayer is interapted: ", e);
        } finally {
            if (mAudioTrack != null) {
                mAudioTrack.flush();
                mAudioTrack.stop();
                mAudioTrack.release();
            }
        }
    }

    private AudioTrack getAudioTrack() { // Lazy loading
        if (mAudioTrack == null) {
            mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, 8000, AudioFormat.CHANNEL_OUT_MONO,
                    AudioFormat.ENCODING_DEFAULT, AVCODEC_MAX_AUDIO_FRAME_SIZE, AudioTrack.MODE_STREAM);
            mAudioTrack.play();
        }
        if (mAudioTrack.getPlayState() != AudioTrack.PLAYSTATE_PLAYING) {
            mAudioTrack.play();
        }
        return mAudioTrack;
    }

}
